package controller.system;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import base.entity.Page;
import entity.role.MyResource;
import entity.role.Role;
import entity.role.RoleResource;
import entity.role.UserRole;
import entity.user.User;
import log.annotation.ControllerAnnotation;
import service.role.IRoleService;
import service.user.IUserService;

@Controller
@RequestMapping("/system")
public class RoleController {
	@Resource
	private IRoleService roleServiceImpl;
	@Resource
	private IUserService userServiceImpl;
	
	/**
	 * 角色管理首页
	 * 
	 * @return
	 */
	@RequestMapping("/permission/rolemanager")
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.system.RoleController", function = "用户管理", methodname = "rolemanager", model = "角色管理", opercation = "加载角色管理菜单", isMenu = true, menuName = "角色管理")
	public String rolemanager() {
		return "/page/system/rolemanager";
	}

	/**
	 * 用户管理首页
	 * 
	 * @return
	 */
	@RequestMapping("/permission/usermanager")
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.system.RoleController", function = "用户管理", methodname = "usermanager", model = "用户CRUD", opercation = "加载用户CRUD菜单", isMenu = true, menuName = "用户管理")
	public String usermanager() {
		return "/page/system/usermanager";
	}

	/**
	 * 功能权限管理
	 * 
	 * @return
	 */
	@RequestMapping("/permission/resourcemanager")
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.system.RoleController", function = "权限设置", methodname = "resourcemanager", model = "功能权限管理", opercation = "加载功能权限管理菜单", isMenu = true, menuName = "功能权限管理")
	public String resourcemanager() {
		return "/page/system/resourcemanager";
	}

	/**
	 * 功能权限分配
	 * 
	 * @return
	 */
	@RequestMapping("/permission/roleresourcemanager")
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.system.RoleController", function = "权限设置", methodname = "roleresourcemanager", model = "功能权限分配", opercation = "加载功能权限分配菜单", isMenu = true, menuName = "功能权限分配")
	public String roleresourcemanager() {
		return "/page/system/roleresourcemanager";
	}
	/**
	 * 数据权限管理
	 * 
	 * @return
	 */
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.system.RoleController", function = "权限设置", methodname = "datamanager", model = "数据权限管理", opercation = "加载数据权限管理菜单", isMenu = true, menuName = "数据权限管理")
	@RequestMapping("/permission/datamanager")
	public String datamanager() {
		return "/page/system/datamanager";
	}
	/**
	 * 数据权限分配
	 * 
	 * @return
	 */
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.system.RoleController", function = "权限设置", methodname = "roledatamanager", model = "数据权限分配", opercation = "加载数据权限分配菜单", isMenu = true, menuName = "数据权限分配")
	@RequestMapping("/permission/roledatamanager")
	public String roledatamanager() {
		return "/page/system/roledatamanager";
	}
	/**
	 * 加载所有角色
	 * 
	 * @param out
	 * @param request
	 * @param pageNo
	 * @param pageSize
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getRolesByPageAndSize")
	public void getRolesByPageAndSize(PrintWriter out, HttpServletRequest request, Integer page, Integer rows) {
		JSONObject data = new JSONObject();
		try {
			JSONArray datas = new JSONArray();
			Page<Role> p = roleServiceImpl.getRolesByPageAndSize(page, rows);
			List<Role> roles = p.getDatas();
			for (Role r : roles) {
				JSONObject role = new JSONObject();
				role.put("id", r.getId());
				role.put("name", r.getName());
				role.put("code", r.getCode());
				datas.add(role);
			}
			data.put("total", p.getTotalRow());
			data.put("rows", datas);
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 增加角色
	 * 
	 * @param out
	 * @param request
	 * @param role
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/addRole")
	public void addRole(PrintWriter out, HttpServletRequest request, Role role) {
		JSONObject data = new JSONObject();
		try {
			roleServiceImpl.addRole(role);
			data.put("flag", true);
		} catch (Exception e) {
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 修改角色
	 * 
	 * @param out
	 * @param request
	 * @param id
	 * @param name
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/updateRole")
	public void updateRole(PrintWriter out, HttpServletRequest request, String id, String name) {
		JSONObject data = new JSONObject();
		try {
			Role role = roleServiceImpl.getRoleById(id);
			role.setName(name);
			roleServiceImpl.updateRole(role);
			data.put("flag", true);
		} catch (Exception e) {
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 删除角色
	 * 
	 * @param out
	 * @param request
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/deleteRole")
	public void deleteRole(PrintWriter out, HttpServletRequest request, String id) {
		JSONObject data = new JSONObject();
		try {
			roleServiceImpl.deleteRole(id);
			data.put("flag", true);
		} catch (Exception e) {
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 根据角色ID查询该角色下的所有用户
	 * 
	 * @param out
	 * @param request
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getUsersByRoleId")
	public void getUsersByRoleId(PrintWriter out, HttpServletRequest request, String id, Integer page, Integer rows) {
		JSONObject data = new JSONObject();
		try {
			Page<UserRole> p = roleServiceImpl.getUsersByRoleId(page, rows, id);
			data.put("total", p.getTotalRow());
			JSONArray datas = new JSONArray();
			List<UserRole> userRoles = p.getDatas();
			for (UserRole userRole : userRoles) {
				JSONObject ur = new JSONObject();
				ur.put("id", userRole.getId());
				ur.put("account", userRole.getUser().getAccount());
				ur.put("name", userRole.getUser().getName());
				ur.put("phone", userRole.getUser().getPhone());
				datas.add(ur);
			}
			data.put("rows", datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 增加用户到指定角色
	 * 
	 * @param out
	 * @param request
	 * @param ids
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/addUserToRole")
	public void addUserToRole(PrintWriter out, HttpServletRequest request, @RequestParam("ids[]") List<String> ids,
			String id) {
		JSONObject data = new JSONObject();
		try {
			Role role = roleServiceImpl.getRoleById(id);
			List<User> users = roleServiceImpl.getAllUsersFromUserRole(role);
			for (User user : users) {
				if (ids.contains(user.getId())) {
					ids.remove(user.getId());
				}
			}
			users.clear();
			users = userServiceImpl.getUsersByIds(ids);
			List<UserRole> userRoles = new ArrayList<>();
			for (User user : users) {
				UserRole userRole = new UserRole();
				userRole.setRole(role);
				userRole.setUser(user);
				userRoles.add(userRole);
			}
			roleServiceImpl.addUserToRole(userRoles);
			data.put("flag", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 增加用户到指定角色
	 * 
	 * @param out
	 * @param request
	 * @param ids
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/deleteUserRole")
	public void deleteUserRole(PrintWriter out, HttpServletRequest request, @RequestParam("ids[]") List<String> ids) {
		JSONObject data = new JSONObject();
		try {
			roleServiceImpl.deleteUserRoleByIds(ids);
			data.put("flag", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 增加受控资源
	 * 
	 * @param out
	 * @param request
	 * @param myResource
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/addResource")
	public void addResource(PrintWriter out, HttpServletRequest request, MyResource myResource, String parentname) {
		JSONObject data = new JSONObject();
		try {
			if (parentname != "") {
				MyResource parent = roleServiceImpl.getResourceByName(parentname);
				if (parent != null) {
					myResource.setParent(parent);
				}
			}
			roleServiceImpl.addResource(myResource);
			data.put("flag", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 分页查询受控资源
	 * 
	 * @param out
	 * @param request
	 * @param page
	 * @param rows
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getResourceByPageAndSize")
	public void getResourceByPageAndSize(PrintWriter out, HttpServletRequest request, Integer page, Integer rows) {
		JSONObject data = new JSONObject();
		try {
			Page<MyResource> p = roleServiceImpl.getResourcesByPageAndSize(page, rows);
			data.put("total", p.getTotalRow());
			JSONArray datas = new JSONArray();
			List<MyResource> resources = p.getDatas();
			for (MyResource resource : resources) {
				JSONObject r = new JSONObject();
				r.put("id", resource.getId());
				r.put("name", resource.getName());
				r.put("url", resource.getUrl());
				r.put("type", resource.getType());
				r.put("activite", resource.getActivite());
				r.put("ordernum", resource.getOrdernum());
				if (resource.getChildrens().size() != 0) {
					r.put("state", "closed");
				} else {
					r.put("state", "open");
				}
				datas.add(r);
			}
			data.put("rows", datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 根据ID加载子资源
	 * 
	 * @param out
	 * @param request
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/loadChildrens")
	public void loadChildrens(PrintWriter out, HttpServletRequest request, String id) {
		JSONObject data = new JSONObject();
		try {
			JSONArray datas = new JSONArray();
			List<MyResource> resources = roleServiceImpl.getResourcesByParentId(id);
			for (MyResource resource : resources) {
				JSONObject r = new JSONObject();
				r.put("id", resource.getId());
				r.put("name", resource.getName());
				r.put("url", resource.getUrl());
				r.put("type", resource.getType());
				r.put("activite", resource.getActivite());
				r.put("parentname", resource.getParent().getName());
				r.put("ordernum", resource.getOrdernum());
				if (resource.getChildrens().size() != 0) {
					r.put("state", "closed");
				} else {
					r.put("state", "open");
				}
				datas.add(r);
			}
			data.put("rows", datas);
			data.put("flag", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 更新资源
	 * 
	 * @param out
	 * @param request
	 * @param myResource
	 * @param parentname
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/updateResource")
	public void updateResource(PrintWriter out, HttpServletRequest request, MyResource myResource, String parentname) {
		JSONObject data = new JSONObject();
		try {
			MyResource resource = roleServiceImpl.getResourceById(myResource.getId());
			resource.setName(myResource.getName());
			resource.setUrl(myResource.getUrl());
			resource.setType(myResource.getType());
			resource.setOrdernum(myResource.getOrdernum());
			MyResource parent = roleServiceImpl.getResourceByName(parentname);
			resource.setParent(parent);
			roleServiceImpl.updateResource(resource);
			data.put("flag", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 更新资源状态
	 * 
	 * @param out
	 * @param request
	 * @param id
	 * @param activite
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/updateResourceState")
	public void updateResourceState(PrintWriter out, HttpServletRequest request, String id, Boolean activite) {
		JSONObject data = new JSONObject();
		try {
			roleServiceImpl.updateResourceState(id, activite);
			data.put("flag", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 删除资源
	 * 
	 * @param out
	 * @param request
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/deleteResource")
	public void deleteResource(PrintWriter out, HttpServletRequest request, String id) {
		JSONObject data = new JSONObject();
		try {
			roleServiceImpl.deleteResourceById(id);
			data.put("flag", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 加载资源树节点
	 * 
	 * @param out
	 * @param request
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getResourceTreeData")
	public void getResourceTreeData(PrintWriter out, HttpServletRequest request) {
		JSONArray data = new JSONArray();
		try {
			List<MyResource> resources = roleServiceImpl.getAllParentResource();
			for (MyResource myResource : resources) {
				JSONObject r = new JSONObject();
				r.put("id", myResource.getId());
				r.put("text", myResource.getName());
				if (myResource.getChildrens().size() > 0) {
					JSONArray children = roleServiceImpl.geResourceChildren(myResource);
					r.put("children", children);
				}
				data.add(r);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 给角色授权
	 * 
	 * @param out
	 * @param request
	 * @param roleIds
	 * @param resourceIds
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/addRoleResource")
	public void addRoleResource(PrintWriter out, HttpServletRequest request,
			@RequestParam("roleIds[]") List<String> roleIds, @RequestParam("resourceIds[]") List<String> resourceIds) {
		JSONObject data = new JSONObject();
		try {
			roleServiceImpl.addRoleResource(roleIds, resourceIds);
			data.put("flag", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 查询当前角色的权限
	 * 
	 * @param out
	 * @param request
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/initCurrentRoleResource")
	public void initCurrentRoleResource(PrintWriter out, HttpServletRequest request, String id) {
		JSONArray datas = new JSONArray();
		try {
			List<RoleResource> roleResources = roleServiceImpl.getCurrentRoleResourceByRoleId(id);
			for (RoleResource roleResource : roleResources) {
				JSONObject data = new JSONObject();
				data.put("id", roleResource.getResource().getId());
				datas.add(data);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.write(datas.toJSONString());
	}

	/**
	 * 获取当前登录用户菜单菜单权限
	 * 
	 * @param out
	 * @param request
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/initCurrentUserMenus")
	public void initCurrentUserMenus(PrintWriter out, HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		JSONArray data = new JSONArray();
		try {
			// 判断当前用户是否是超级管理员（如果是，则直接加载所有权限）
			Boolean isSuperManager = roleServiceImpl.isSuperMnager(user.getId());
			// 查询用户所有顶级菜单权限
			List<MyResource> topRoleResources = roleServiceImpl.getUserMenusByUserId(user.getId(), true,isSuperManager);
			// 查询用户所有菜单权限
			List<MyResource> childrenRoleResources = roleServiceImpl.getUserMenusByUserId(user.getId(), false,isSuperManager);
			// 遍历顶级菜单，获取顶级菜单下用户有的子菜单
			for (MyResource key : topRoleResources) {
				JSONObject menu = new JSONObject();
				menu.put("id", key.getId());
				menu.put("text", key.getName());
				menu.put("url", key.getUrl());
				if (key.getChildrens().size() != 0) {
					JSONArray children = roleServiceImpl.geResourceChildren(key, childrenRoleResources,isSuperManager);
					menu.put("children", children);
				}
				data.add(menu);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 清空该角色权限
	 * 
	 * @param out
	 * @param request
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/clearRoleResource")
	public void clearRoleResource(PrintWriter out, HttpServletRequest request,
			@RequestParam("roleIds[]") List<String> roleIds) {
		JSONObject data = new JSONObject();
		try {
			roleServiceImpl.deleteOldRoleResources(roleIds);
			data.put("flag", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data.put("flag", false);
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}
}
